package channelp

import (
	"fmt"
	"time"
)

func Play() {
	//case 1 buffer channel
	c := make(chan int, 10)
	defer close(c)
	c <- 1
	fmt.Println(<-c)

	//case 2 hand over channel
	c1 := make(chan string)
	defer func() { close(c1) }()
	go func() {
		time.Sleep(time.Second)
		c1 <- "hello"
	}()
	fmt.Println(<-c1)

	//case3 select & readonly channel
	c2 := make(chan string, 5)
	c3 := make(chan string, 5)
	defer func() {
		close(c2)
		close(c3)
	}()
	monitor(c2, c3)
	go func() {
		for {
			time.Sleep(time.Second)
			c2 <- "c2"
		}
	}()
	go func() {
		for {
			time.Sleep(time.Second)
			c3 <- "c3"
		}
	}()
	//case 4 range channel
	c4 := make(chan string ,10)
	go func() {
		for i:=0; i<11; i++ {
			c4 <- "hi"
		}
	}()
	go func() {
		time.Sleep(time.Second*3)
		fmt.Println("c4 closed")
		close(c4)
	}()
	//stop range until c4 closed & no content in the channel
	for x := range c4 {
		time.Sleep(time.Second)
		fmt.Println(x)
	}

	//case 5 read by timeout
	c5 := make(chan string, 1)
	go func() {
		c5 <- "c5"
	}()
	readByTime(c5)
	go func() {
		time.Sleep(time.Second*2)
		c5 <- "c5"
	}()
	readByTime(c5)

}
// write only channel `c2 chan<- string`
// read only channel `c2 <-chan string`
func monitor(c2 <-chan string, c3 <-chan string){
	go func() {
		for {
			select {
			case e, ok := <-c2:
				if ok {
					fmt.Println(e)
				}
			case e, ok := <-c3:
				if ok {
					fmt.Println(e)
				}
			}
		}
	}()
}

func readByTime(t <-chan string) {
	select {
		case e, ok := <-t:
			if ok {
				fmt.Println(e)
			}
		case <- time.After(time.Second):
			panic("time out")

	}
}
